package com.redlight.base;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import com.redlight.utils.ApplicationContextProvider;

/**
 * Created by chao on 2019/1/9.
 */
public class EhCacheUtils {
    private static CacheManager cacheManager = (CacheManager) ApplicationContextProvider.getBean("ehCacheManagerFactory");
    public static final String EH_userCache = "Eh_userCache";
    public static final String Eh_sysCache = "Eh_sysCache";

    public EhCacheUtils() {
    }

    public static <T> T get(String key) {
        return get("Eh_sysCache", key);
    }

    public static void put(String key, Object value) {
        put("Eh_sysCache", key, value);
    }

    public static void remove(String key) {
        remove("Eh_sysCache", key);
    }

    public static <T> T get(String cacheName, String key) {
        Element element = getCache(cacheName).get(key);
        return element == null?null: (T) element.getObjectValue();
    }

    public static void put(String cacheName, String key, Object value) {
        Element element = new Element(key, value);
        getCache(cacheName).put(element);
    }

    public static void remove(String cacheName, String key) {
        getCache(cacheName).remove(key);
    }

    public static Cache getCache(String cacheName) {
        Cache cache = cacheManager.getCache(cacheName);
        if(cache == null) {
            cacheManager.addCache(cacheName);
            cache = cacheManager.getCache(cacheName);
            cache.getCacheConfiguration().setEternal(true);
        }

        return cache;
    }

    public static CacheManager getCacheManager() {
        return cacheManager;
    }
}
